<template>
	<view>
		<view class="cardView">
			<uni-title type="h2" title="医疗器械经营许可证数据统计" align="center"></uni-title>
			<businessTable :headers="tableHeaders" :tableData="checkResults" />
		</view>
		<view class="cardView">
			<uni-title type="h2" title="医疗器械经营许可证数据分析" align="center"></uni-title>

			<uni-section title="经营方式" type="line">
				<view style="margin:20px">
					<businessTable :tableTitle="Text2002" :headers="checkOperNumber" :tableData="checkOperResults" />
				</view>
				<view class="charts-box">
					<!-- 这里因为是页面初始化默认显示的，如果不给reshow也会显示，切换回来也不会变成白板，但切换到其他tab后，改变了窗口尺寸再切换回来后，没有reshow则不会根据改变后的窗口自动适应（除非在当前tab显示的情况下再变更窗口大小才会自适应），所以建议加上reshow属性 -->
					<qiun-data-charts :ontouch="true" type="column" :chartData="dataAnalysis" />
				</view>
			</uni-section>


			<uni-section title="经营范围" type="line">
				<view style="margin:20px">
					<businessTable :tableTitle="Text2007" :headers="bidTypeList" :tableData="bidTypeResults" />
				</view>
			</uni-section>

			<view class="charts-box">
				<qiun-data-charts type="bar"
					:opts="{padding: [15,55,0,5],xAxis:{max:40},extra:{bar:{linearType:'custom',barBorderCircle:true}}}"
					:chartData="mainTypeList" />

			</view>

			<view class="charts-box">
				<qiun-data-charts type="bar"
					:opts="{padding: [15,55,0,5],xAxis:{max:40},extra:{bar:{linearType:'custom',barBorderCircle:true}}}"
					:chartData="sceneTypeListChart" />

			</view>


			<uni-section title="不符合项统计" type="line">
				<view style="margin:20px">
					<!--	<businessTableGroup :group-size="3" :headers="twoList" :tableData="twoResults" />-->
					<businessTableNoTitle :data="twoResults" :items-per-row="2" />


				</view>
				<view class="charts-box">
					<!-- 这里因为是页面初始化默认显示的，如果不给reshow也会显示，切换回来也不会变成白板，但切换到其他tab后，改变了窗口尺寸再切换回来后，没有reshow则不会根据改变后的窗口自动适应（除非在当前tab显示的情况下再变更窗口大小才会自适应），所以建议加上reshow属性 -->
					<qiun-data-charts :opts="{enableScroll:true,xAxis:{scrollShow:true,itemCount:4,disableGrid:true}}"
						:ontouch="true" type="column" :chartData="twoListChart" />
				</view>


			</uni-section>

		</view>

	</view>

</template>

<script>
	import businessTableGroup from './business-table-group.vue'
	import businessTable from './business-table.vue'
	import businessTableNoTitle from './business-table-noTitle.vue'
	import demodata from '@/mockdata/demodata.json';
	import {
		getMedicalDict,
	} from '@/api/order'
	import {
		statistics,
		typeOfMatter,
		dataAnalysis,
		mainType,
		checkResult,
		foodBusinessII,
		foodBusinessFive,
		foodMedicalDataAnalysis,
		foodMedicalProjects,
		foodMedical2002,
		foodMedical2007,
		foodMedicalNoConformTo,
		foodMedicalStatistics
	} from '@/api/analysis.js'
	export default {
		components: {
			businessTable,
			businessTableGroup,
			businessTableNoTitle
		},
		props: {
			type: String,
			// 新增时间参数
			startTime: {
				type: String,
				default: ''
			},
			endTime: {
				type: String,
				default: ''
			}
		},
		watch: {
			startTime: {
				handler(newVal) {
					this.request.startTime = newVal
					this.refreshAllData()
				},
				immediate: true
			},
			endTime: {
				handler(newVal) {
					this.request.endTime = newVal
					this.refreshAllData()
				},
				immediate: true
			}
		},
		data() {
			const now = new Date()
			const defaultStart = `${now.getFullYear()}-01` // 默认当年1月
			const defaultEnd = `${now.getFullYear()}-12` // 默认当年12月
			return {
				request: {
					startTime: this.startTime || defaultStart,
					endTime: this.endTime || defaultEnd
				},

				Text2002: '2002版经营范围',
				Text2007: '2007版经营范围',
				tableHeaders: [{
						label: '事项名称',
						prop: 'bidType'
					},
					{
						label: '受理量',
						prop: 'accept'
					},
					{
						label: '通过现场核查',
						prop: 'pass'
					},
					{
						label: '不通过现场核查',
						prop: 'noPass'
					},
					{
						label: '撤回',
						prop: 'revoke'
					}
				],
				checkResults: [], // 初始化为空，接口返回后更新
				checkOperNumber: [],
				checkOperResults: [],

				bidTypeList: [],
				bidTypeResults: [],


				// 主体类别
				containerTypeList: [],
				containerTypeResults: [],
				sceneTypeList: [],
				sceneTypeResults: [],

				twoList: [],
				twoResults: [],

				fiveList: [{
						label: '核查内容',
						prop: 'title'
					},
					{
						label: '不符合判定',
						prop: 'noPass'
					},
					{
						label: '不符合占比',
						prop: 'invalidPercentage'
					}
				],
				fiveResults: [],
				chartsDataColumn1: {},
				dataAnalysis: {},
				typeOfMatterList: {},
				mainTypeList: {},
				sceneTypeListChart: {},
				twoListChart: {},
				fiveListChart: {}
			}
		},
		watch: {
			type() {
				this.getStatistics();
				this.getDataAnalysis();
				this.getTypeOfMatter();
				this.getMainType();
				this.getCheckResult();
				this.getFoodBusinessII();
				this.getFoodBusinessFive()
			}
		},
		mounted() {
			this.getStatistics();
			this.getDataAnalysis();
			this.getTypeOfMatter();
			this.getMainType();
			this.getCheckResult();
			this.getFoodBusinessII();
			this.getFoodBusinessFive()
		},
		methods: {
			refreshAllData() {
				if (!this.startTime || !this.endTime) return

				this.getStatistics()
				this.getDataAnalysis()
				this.getTypeOfMatter()
				this.getMainType()
				this.getCheckResult()
				this.getFoodBusinessII()
				this.getFoodBusinessFive()
			},
			//获取食品经营许可数据统计数据源
			async getStatistics() {
				try {
					const res = await foodMedicalStatistics(this.request);
					if (res.code === 0) {

						// 处理表格数据
						this.checkResults = res.data.map(item => ({
							bidType: item.bidType,
							revoke: item.revoke,
							accept: item.accept,
							pass: item.pass,
							noPass: item.noPass
						}));


					} else {
						throw new Error(res?.msg || '接口返回异常');
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},
			//获取食品经营许可数据分析数据源
			async getDataAnalysis() {
				try {
					const res = await foodMedicalDataAnalysis(this.request);
					if (res.code === 0) {
						// 动态生成表头
						this.checkOperNumber = res.data.map(item => ({
							label: item.label,
							prop: item.label // 直接使用label作为prop
						}));

						// 动态构造表格数据
						const dynamicData = {};
						res.data.forEach(item => {
							dynamicData[item.label] = item.value || '0';
						});
						this.checkOperResults = [dynamicData];

						// 生成图表数据
						this.dataAnalysis = {
							categories: res.data.map(item => item.label),
							series: [{
								name: "经营方式",
								data: res.data.map(item => parseFloat(item.accountFor) || 0),
								format: 'yAxisDemoMix'
							}]
						};
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},
			//经营范围
			async getTypeOfMatter() {
				try {
					const res = await foodMedicalProjects(this.request);
					if (res.code === 0) {
						// 处理表头（包含总量）
						this.bidTypeList = res.data.map(item => ({
							label: item.label,
							prop: item.label
						}));

						// 处理表格数据（保持原始value值）
						const tableData = {};
						res.data.forEach(item => {
							tableData[item.label] = item.value; // 保留原始字符串值
						});
						this.bidTypeResults = [tableData];

						/*
												// 生成图表数据（包含总量）
												this.typeOfMatterList = {
													categories: res.data.map(item => item.label),
													series: [{
														name: "事项占比",
														data: res.data.map(item => {
															return parseFloat(item.accountFor) || 0
														}),
														format: 'yAxisDemoMix'
													}]
												};
												*/
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},
			//食品经营许-主体类别
			async getMainType() {
				try {
					const res = await foodMedical2002(this.request);
					if (res.code === 0) {

						// 生成图表数据（包含总量）
						this.mainTypeList = {
							categories: res.data.map(item => item.LABLE_NAME),
							series: [{
								name: "2002经营范围",
								data: res.data.map(item => {
									return parseFloat(item.accountFor) || 0
								}),
								format: 'yAxisDemoMix'
							}]
						};
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},

			//2007结果范围
			async getCheckResult() {
				try {
					const res = await foodMedical2007(this.request);
					if (res.code === 0) {

						// 生成图表数据（包含总量）
						this.sceneTypeListChart = {
							categories: res.data.map(item => item.LABLE_NAME),
							series: [{
								name: "2007经营范围",
								data: res.data.map(item => {
									return parseFloat(item.accountFor) || 0
								}),
								format: 'yAxisDemoMix'
							}]
						};
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},
			//获取食品经营二类
			async getFoodBusinessII() {
				try {
					const res = await foodMedicalNoConformTo(this.request);
					if (res.code === 0) {

						// 直接使用接口返回的 data 数组即可
						this.twoResults = res.data.map(item => ({
							label: item.label,
							value: item.value,
							accountFor: item.accountFor // 如果需要显示占比可保留
						}));


						// 生成图表数据
						this.twoListChart = {

							categories: res.data.map(item => item.label),
							series: [{
								name: "不符合占比",
								data: res.data.map(item => parseFloat(item.accountFor) || 0),
								format: 'yAxisDemoMix'
							}]
						};
						/*
						      // 生成图表数据
						      this.twoListChart = {
						        categories: res.data.map(item => item.title),
						        series: [{
						          name: "不符合数量",
						          data: res.data.map(item => parseInt(item.noPass) || 0)
						        }, {
						          name: "总核查项",
						          data: res.data.map(item => parseInt(item.total) || 0)
						        }]
						      };
						
						      // 如果需要显示百分比数据（额外示例）
						      this.chartsDataColumn1 = {
						        categories: res.data.map(item => item.title),
						        series: [{
						          name: "不符合率",
						          data: res.data.map(item => 
						            parseFloat(item.invalidPercentage.replace('%', '')) || 0
						          ),
						  format: 'yAxisDemoMix'
						        }]
						      };
						*/
					} else {
						throw new Error(res?.msg || '接口返回异常');
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},
			//获取食品经营五类
			async getFoodBusinessFive() {
				try {
					const res = await foodBusinessFive(this.request);
					if (res.code === 0) {
						// 处理表格数据
						this.fiveResults = res.data.map(item => ({
							title: item.title,
							noPass: item.noPass,
							invalidPercentage: item.invalidPercentage
						}));


						this.fiveListChart = {

							categories: res.data.map(item => item.title),
							series: [{
								name: "第五类不符合占比",
								data: res.data.map(item => parseFloat(item.invalidPercentage) || 0),
								format: 'yAxisDemoMix'
							}]
						};
						/*
						// 生成图表数据
						this.fiveListChart = {
							categories: res.data.map(item => item.title),
							series: [{
								name: "不符合数量",
								data: res.data.map(item => parseInt(item.noPass) || 0)
							}, {
								name: "总核查项",
								data: res.data.map(item => parseInt(item.total) || 0)
							}]
						};

						// 如果需要显示百分比数据（额外示例）
						this.chartsDataColumn1 = {
							categories: res.data.map(item => item.title),
							series: [{
								name: "不符合率",
								data: res.data.map(item =>
									parseFloat(item.invalidPercentage.replace('%', '')) || 0
								)
							}]
						};
*/

					} else {
						throw new Error(res?.msg || '接口返回异常');
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					});
				}
			},
			getServerData() {
				setTimeout(() => {
					//因部分数据格式一样，这里不同图表引用同一数据源的话，需要深拷贝一下构造不同的对象
					//开发者需要自行处理服务器返回的数据，应与标准数据格式一致，注意series的data数值应为数字格式
					this.chartsDataColumn1 = JSON.parse(JSON.stringify(demodata.Column))
					console.log(this.chartsDataColumn1)
				}, 1500);
			},

		}
	}
</script>

<style lang="scss">
	.page {
		background-color: #e9f1fe;
		padding: 20px;
		height: 100%;
	}

	.cardView {
		margin-bottom: 10px;
		padding: 15px;
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
	}

	.charts-box {
		width: 90vw;
		height: 10vh;
		min-height: 300rpx;
		/* 兼容小程序 */
	}

	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */

		.button-save {
			margin-bottom: 10px;
		}

		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */

		}
	}
</style>